package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.imageView.strategy.ImageLoader;
import com.fgs.common.manager.ActivityManager;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.widget.itemView.SettingItemView;
import com.tianhui.consignortwofei.BuildConfig;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.Config;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.CapitalData;
import com.tianhui.consignortwofei.mvp.model.enty.CapitalInfo;
import com.tianhui.consignortwofei.mvp.model.enty.ConsignorInfo;
import com.tianhui.consignortwofei.mvp.model.enty.UserInfo;
import com.tianhui.consignortwofei.mvp.ui.activity.AboutActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.AccountDetailActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.BaoJiaWebActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.ChangePasswordActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.ConsignorListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.FeedBackActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.LegalNoticeActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.LoginActivityNew;
import com.tianhui.consignortwofei.mvp.ui.activity.MyTwoCodeActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OnlyLookQuotListTwoActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.QuotationListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.SettingActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.driver.DriverListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle.VehicleFrontActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.vehicle.VehicleListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.auth.ConsignorAuthActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.carrier.CarrierListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.fujian.FuJianListTwoActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.fujian.TaiTouListTwoActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.fujian.UnHuiKuanListActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.HeTongActivityNew;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.HeTongShenTwoActivity;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.role.RoleController;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.imageview.RadiusImageView;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @author fgs
 * @date 2020/9/8
 * @description
 **/
public class MineFragment extends BaseFragment {


    @BindView(R.id.fragment_mine_swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.fragment_mine_nameTextView)
    TextView mNameTextView;
    @BindView(R.id.fragment_mine_headRadiusImageView)
    RadiusImageView mHeadImageView;
    @BindView(R.id.fragment_mine_balanceTextView)
    TextView mBalanceTextView;
    @BindView(R.id.fragment_mine_switchAccountTextView)
    TextView mSwitchAccountTextView;

    @BindView(R.id.fragment_mine_switchUrlSettingItemView)
    SettingItemView mSwitchUrlSettingItemView;
    @BindView(R.id.fragment_mine_driverSettingItemView)
    SettingItemView mDriverSettingItemView;
    @BindView(R.id.fragment_mine_driverCarSettingItemView)
    SettingItemView mDriverCarSettingItemView;
    @BindView(R.id.fragment_mine_carrierSettingItemView)
    SettingItemView mCarrierSettingItemView;
    @BindView(R.id.fragment_mine_dataPerfectionSettingItemView)
    SettingItemView mDataPerfectionSettingItemView;


    @BindView(R.id.tv_change_pass)
    TextView tv_change_pass;


    //公司名
    @BindView(R.id.fragment_mine_company)
    TextView fragment_mine_company;
    //二维码
    @BindView(R.id.fragment_mine_saoItemView)
    SettingItemView fragment_mine_saoItemView;

    @BindView(R.id.fragment_mine_baojia)
    SettingItemView fragment_mine_baojia;
    @BindView(R.id.fragment_baojia_liebiao)
    SettingItemView fragment_baojia_liebiao;
    @BindView(R.id.fragment_mine_baojia_look)
    SettingItemView fragment_mine_baojia_look;

    @BindView(R.id.fragment_mine_hetong)
    SettingItemView fragment_mine_hetong;
    @BindView(R.id.fragment_shenpi_hetong)
    SettingItemView fragment_shenpi_hetong;
    @BindView(R.id.siv_weifujian)
    SettingItemView siv_weifujian;
    @BindView(R.id.siv_huantaitou)
    SettingItemView siv_huantaitou;
    @BindView(R.id.siv_unreason)
    SettingItemView siv_unreason;


    private UserInfoModel mUserInfoModel;
    private ArrayList<ConsignorInfo> mConsignorInfoList;

    public MineFragment() {
        // Required empty public constructor
    }

    @Override
    protected boolean isNeedLazyLoad() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected CommonView createView() {
        return null;
    }

    @Override
    protected CommonPresenter createPresenter() {
        return null;
    }

    @Override
    protected void init() {
        if (BuildConfig.BUILD_TYPE.equals("debug")) {
            mSwitchUrlSettingItemView.setVisibility(View.VISIBLE);
        } else {
            mSwitchUrlSettingItemView.setVisibility(View.GONE);
        }

        mUserInfoModel = new UserInfoModel();
        requestUserInfo();
        initListener();
    }


    private void initListener() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestUserInfo();
            }
        });
    }

    private void requestUserInfo() {

        mUserInfoModel.userInfoModel(getContext(), false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<UserInfo>>() {

            @Override
            public void onNext(CommonResponse<UserInfo> commonResponse) {

                if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }

                if (commonResponse.getCode() == 20000) {
                    UserInfo userInfo = commonResponse.getData();
                    if (userInfo != null && userInfo.profile != null) {
                        if (!TextUtils.isEmpty(userInfo.profile.name)) {
                            mNameTextView.setText(userInfo.profile.name);
                        }
//                        mNameTextView.setText(userInfo.profile.name);
                        if (!TextUtils.isEmpty(userInfo.profile.avatar)) {
                            ImageLoader.init().loadImageWithUrl(mHeadImageView, Config.baseImageUrl + userInfo.profile.avatar + ".jpg", R.mipmap.icon_head);
                        }
                        SharedPreferenceManager.getInstance().setConsignorId(userInfo.profile.id);
                        SharedPreferenceManager.getInstance().setRoleId(userInfo.profile.roleinfoid);
                        SharedPreferenceManager.getInstance().setConsignorName(userInfo.profile.name);
                        SharedPreferenceManager.getInstance().setPhone(userInfo.profile.phone);
//                        requestCapitalInfo(userInfo.profile.id);
                        requestCapitalInfo(userInfo.profile.roleinfoid,userInfo);
                        requestConsignorGroupListInfo(userInfo.profile.id);

                        RoleController.getInstance().setRole(userInfo.profile);

                        EventBus.getDefault().post(new CommonEvent(EventWhat.CHANGE_TAB_FRAGMENT.getValue()));
                        //是否显示统计图View
                        EventBusManage.refreshStatisticsView();
                        refreshCarrierManageView();

                    }
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
                if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    //货权选择列表
    private void requestConsignorGroupListInfo(String id) {
        if (TextUtils.isEmpty(id)) return;
        Map<String, String> map = new HashMap<>();
        map.put("userId", id);
        mUserInfoModel.consignorGroupListModel(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<ArrayList<ConsignorInfo>>>() {
            @Override
            public void onNext(CommonResponse<ArrayList<ConsignorInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    mConsignorInfoList = commonResponse.getData();
                    if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {
                        mSwitchAccountTextView.setVisibility(View.VISIBLE);
                    } else {
                        mSwitchAccountTextView.setVisibility(View.GONE);
                    }
                } else {
                    LogUtil.print(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                LogUtil.print(e.message);
            }
        });
    }

    private void requestCapitalInfo(String id,UserInfo userInfo) {
        Map<String, String> map = new HashMap<>();
//        map.put("userId", id);
        map.put("customerno", id);
        mUserInfoModel.capitalInfoModel(getContext(), map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<CapitalData>>() {

            @Override
            public void onNext(CommonResponse<CapitalData> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    CapitalData capitalData = commonResponse.getData();

                   int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
                    if (2== rolePosition){
                        //2 销售，3物流

                    }else {
                        if (!TextUtils.isEmpty(capitalData.customername)) {
                            if (!TextUtils.isEmpty(userInfo.profile.name)) {
                                mNameTextView.setText(capitalData.customername+"("+userInfo.profile.name+")");
                            }else {
                                mNameTextView.setText(capitalData.customername);
                            }
                        }
                    }

                    if (capitalData != null) {
                        CapitalInfo capitalInfo = capitalData.customerCapital;
                        if (capitalInfo != null) {
                            if (!TextUtils.isEmpty(capitalInfo.available)) {
                                BigDecimal result = new BigDecimal(capitalInfo.available);
                                mBalanceTextView.setText(result + "元");
                            } else {
                                mBalanceTextView.setText("0元");
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

            }
        });
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_CONSIGNOR_INFO:
                requestUserInfo();
                break;
            case EVENT_REFRESH_CARRIER_MANAGE_VIEW:
                refreshCarrierManageView();
                break;
        }
    }

    private void refreshCarrierManageView() {

        int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
        if (2== rolePosition){
            //2 销售，3物流
            fragment_mine_baojia.setVisibility(View.VISIBLE);
            fragment_baojia_liebiao.setVisibility(View.VISIBLE);
            fragment_mine_baojia_look.setVisibility(View.VISIBLE);
            fragment_mine_hetong.setVisibility(View.VISIBLE);

            fragment_shenpi_hetong.setVisibility(View.VISIBLE);
            siv_weifujian.setVisibility(View.VISIBLE);
            siv_huantaitou.setVisibility(View.VISIBLE);
            siv_unreason.setVisibility(View.VISIBLE);

        }else {
            fragment_mine_baojia.setVisibility(View.GONE);
            fragment_baojia_liebiao.setVisibility(View.GONE);
            fragment_mine_baojia_look.setVisibility(View.GONE);
            fragment_mine_hetong.setVisibility(View.GONE);

            fragment_shenpi_hetong.setVisibility(View.GONE);
            siv_weifujian.setVisibility(View.GONE);
            siv_huantaitou.setVisibility(View.GONE);
            siv_unreason.setVisibility(View.GONE);

        }

        boolean isShowCarrierManageView = RoleController.getInstance().isShowCarrierManageView();
        VehicleFrontActivity.getXinDIInfo(getActivity());
        if (isShowCarrierManageView) {
            mDriverSettingItemView.setVisibility(View.VISIBLE);
            mDriverCarSettingItemView.setVisibility(View.VISIBLE);
            mCarrierSettingItemView.setVisibility(View.VISIBLE);
        } else {
            mDriverSettingItemView.setVisibility(View.GONE);
            mDriverCarSettingItemView.setVisibility(View.GONE);
            mCarrierSettingItemView.setVisibility(View.GONE);
        }

        boolean isShowConsignorInfo = RoleController.getInstance().isShowPerfectData();
        if (isShowConsignorInfo) {
            mDataPerfectionSettingItemView.setVisibility(View.VISIBLE);
        } else {
            mDataPerfectionSettingItemView.setVisibility(View.GONE);
        }
    }


    @OnClick(R.id.fragment_mine_saoItemView)
    public void twoCode() {
        openActivity(MyTwoCodeActivity.class);
    }

    @OnClick(R.id.fragment_mine_feedBackSettingItemView)
    public void feedBack() {
        openActivity(FeedBackActivity.class);
    }

    @OnClick(R.id.fragment_mine_legalNoticeSettingItemView)
    public void legalNotice() {
        openActivity(LegalNoticeActivity.class);
    }


    @OnClick(R.id.fragment_mine_baojia)
    public void baoJia() {
        //报价管理
        Bundle bundle=new Bundle();
        bundle.putInt("lookType",1);
        openActivity(QuotationListActivity.class,bundle);


    }

    @OnClick(R.id.fragment_mine_baojia_look)
    public void baoJiaLook() {
        //查看报价
//        Bundle bundle=new Bundle();
//        bundle.putInt("lookType",2);
//        openActivity(OnlyLookQuotListActivity.class,bundle);
        openActivity(BaoJiaWebActivity.class);
    }

    @OnClick(R.id.fragment_baojia_liebiao)
    public void baoJiaLookLieBiao() {
        //报价列表
        Bundle bundle=new Bundle();
        bundle.putInt("lookType",2);
        openActivity(OnlyLookQuotListTwoActivity.class,bundle);

    }



    @OnClick(R.id.fragment_mine_hetong)
    public void heTongLook() {
        //提交合同
//        Bundle bundle=new Bundle();
//        bundle.putInt("lookType",2);
//        openActivity(OnlyLookQuotListActivity.class,bundle);
        openActivity(HeTongActivityNew.class);
    }

    @OnClick(R.id.fragment_shenpi_hetong)
    public void heTongshenpi() {
        //审核合同
//        Bundle bundle=new Bundle();
//        bundle.putInt("lookType",2);
//        openActivity(OnlyLookQuotListActivity.class,bundle);
//        openActivity(HeTongShenActivity.class);
        openActivity(HeTongShenTwoActivity.class);
    }



    @OnClick(R.id.siv_weifujian)
    public void fujianHeTong() {
        //附件合同
        openActivity(FuJianListTwoActivity.class);
//        openActivity(FuJianListActivity.class);

    }

    @OnClick(R.id.siv_huantaitou)
    public void huanTaiTou() {
        //换抬头
        openActivity(TaiTouListTwoActivity.class);


    }

    @OnClick(R.id.siv_unreason)
    public void unReason() {
        //欠款信息
        openActivity(UnHuiKuanListActivity.class);


    }




    @OnClick(R.id.fragment_mine_accountDetailTextView)
    public void accountDetail() {
        openActivity(AccountDetailActivity.class);
    }

    @OnClick(R.id.fragment_mine_switchUrlSettingItemView)
    public void switchUrl() {
        showSwitchDialog();
    }

    @OnClick(R.id.fragment_mine_driverSettingItemView)
    public void driverManage() {
        openActivity(DriverListActivity.class);
    }

    @OnClick(R.id.fragment_mine_aboutSettingItemView)
    public void about() {
        openActivity(AboutActivity.class);
    }

    @OnClick(R.id.fragment_mine_driverCarSettingItemView)
    public void vehicleManage() {
        openActivity(VehicleListActivity.class);
    }

    @OnClick(R.id.fragment_mine_carrierSettingItemView)
    public void carrierManage() {
        openActivity(CarrierListActivity.class);
    }

    @OnClick(R.id.fragment_mine_dataPerfectionSettingItemView)
    public void consignorAuth() {
        openActivity(ConsignorAuthActivity.class);
    }

    @OnClick(R.id.tv_change_pass)
    public void changePass() {
        openActivity(ChangePasswordActivity.class);
    }


    private void showSwitchDialog() {
        new MaterialDialog.Builder(getContext())
                .title("切换地址")
                .items(R.array.array_base_url)
                .itemsCallbackSingleChoice(
                        -1,
                        new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                if (which == 0) { // demo
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseWebUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseImageUrl("http://demo.tianhuihaojun.com/picustomer/");
                                } else if (which == 1) { //cnor
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseWebUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseImageUrl("https://cnor.tianhuihaojun.com/picustomer/");
                                } else if (which == 6){
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                    SharedPreferenceManager.getInstance().setBaseImageUrl("http://192.168.3.216:8082/picture/getImgStream?idFile=");
                                }else {
                                    SharedPreferenceManager.getInstance().setBaseUrl(text.toString());
                                }
                                ActivityManager.getInstance().finishAllActivity();
                                System.exit(0);
                                return true;
                            }
                        })
                .show();
    }

    @OnClick(R.id.fragment_mine_logoutTextView)
    public void logout() {
        new MaterialDialog.Builder(getContext())
                .content("确定要退出吗？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        HomeFragment.firstShow=true;
                        SharedPreferenceManager.getInstance().setToken("");
                        ActivityManager.getInstance().finishAllActivity();
                        openActivity(LoginActivityNew.class);
                    }
                })
                .show();

    }

    @OnClick(R.id.fragment_mine_switchAccountTextView)
    public void switchAccount() {
        if (mConsignorInfoList != null && mConsignorInfoList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(KeyValue.KEY_CONSIGNOR_LIST, mConsignorInfoList);
            openActivity(ConsignorListActivity.class, bundle);
        }
    }

    @OnClick(R.id.fragment_mine_settingImageView)
    public void setting() {
        openActivity(SettingActivity.class);
    }
}
